package agency.tango.materialintroscreen.parallax;

import agency.tango.materialintroscreen.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;
import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @ProjectName: material-intro-screen-master
 * @Package: agency.tango.materialintroscreen.parallax
 * @ClassName: ParallaxDependentLayout
 * @Description: 视察试图在AbilitySlice中的使用 根据容器内各个子控件在水平方向的位置 随着滑动按比例偏移子控件
 * @CreateDate: 2021/4/12 17:12
 * @UpdateDate: 2021/4/12 17:12
 * @UpdateRemark: 暂无
 * @Version: 1.0
 */
public abstract class ParallaxAbilitySlice extends AbilitySlice implements Parallaxable {

    /**
     * 根节点控件
     */
    protected Component mRootView;
    /**
     * 视差布局
     */
    protected Parallaxable parallaxLayout;

    public ParallaxAbilitySlice() {
    }

    @Override
    protected final void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(getLayoutId());
        initView();
        parallaxLayout = findParallaxLayout(getRootView());
    }

    /**
     * 初始化控件
     */
    protected abstract void initView() ;

    /**
     * 获取布局ID
     *
     * @return 布局ID
     */
    protected abstract int getLayoutId();


    /**
     * 获取ParallaxLayout
     *
     * @param root 根节点控件
     * @return 根节点及其子类里面包含的ParallaxLayout
     */
    public Parallaxable findParallaxLayout(Component root) {
        Queue<Component> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Component child = queue.remove();
            if (child instanceof Parallaxable) {
                return (Parallaxable) child;
            } else if (child instanceof ComponentContainer) {
                ComponentContainer viewGroup = (ComponentContainer) child;
                for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) {
                    queue.add(viewGroup.getComponentAt(i));
                }
            } else {
                LogUtil.info("ParallaxComponentContainer", "findParallaxLayout");
            }
        }
        return new ParallaxDirectionalLayout(null);
    }

    @Override
    public void setOffset(float offset) {
        if (parallaxLayout != null) {
            parallaxLayout.setOffset(offset);
        }
    }

    /**
     * 获取根控件
     *
     * @return 根控件
     */
    protected abstract @NotNull Component getRootView();

}
